'''
Created on 2013. 5. 13.

@author: Lee
'''
from kr.community.configure import JINJA_ENVIRONMENT
from kr.community.gaesessions import get_current_session
from kr.community.models import Users
import hashlib
import webapp2

class LoginPage(webapp2.RequestHandler):
    '''
        Login Page
    '''


    def get(self):
        session = get_current_session()
        template_values = {}
        template = None
        if session.is_active():
            template = JINJA_ENVIRONMENT.get_template('result_msg.html')
        else:
            template = JINJA_ENVIRONMENT.get_template('login.html')
        
        self.response.write(template.render(template_values))
        
    def post(self):
        session = get_current_session()
        
        user_email = self.request.POST['user_email']
        user_passwd = self.request.POST['passwd']
        result_msg = ""
        
        user_query = Users.query(Users.user_email == user_email)
        
        if user_query.count() == 0:
            result_msg = "Not existing email"
        else:
            user_entry = user_query.get()
            hash_func = hashlib.md5(user_passwd)
            if user_entry.user_passwd != hash_func.hexdigest():
                result_msg = "Wrong password"
            elif user_entry.user_auth == 0:
                result_msg = "Your account is NOT certified."
            else:
                if session.is_active():
                    session.terminate()
                session['user'] = user_entry.key.urlsafe()
                self.redirect("/")
                return
        
        template_values = {}
        template_values['error_msg'] = result_msg
        template = JINJA_ENVIRONMENT.get_template('login.html')
        
        self.response.write(template.render(template_values))